package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.AddressBook;
import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.entity.User;
import com.sky.entity.ShoppingCart;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.socket.*;
import com.sky.service.OrderService;

import com.sky.utils.WeChatPayUtil;
import com.sky.vo.*;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.client.WebSocketClient;
import org.springframework.web.socket.sockjs.transport.session.WebSocketServerSockJsSession;

import java.io.IOException;
import java.math.BigDecimal;


import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {


    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private AddressBookMapper addressBookMapper;

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WeChatPayUtil weChatPayUtil;

    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * 用户提交订单
     *
     * @param ordersSubmitDTO
     * @return
     */
    @Override
    @Transactional
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {

        //异常情况的处理（收货地址为空、购物车为空）
        Long userId = BaseContext.getCurrentId();
        log.info("接收到的前端的信息为：{}", ordersSubmitDTO);
        //根据前端传过来的地址簿id查询地址
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null) {
            throw new OrderBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        //根据用户的id查询用户的购物车是否有数据
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(userId);
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.list(shoppingCart);
        if (shoppingCartList == null || shoppingCartList.size() == 0) {
            throw new OrderBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        //查询当前用户的购物车数据


        //构造订单数据
        Orders order = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, order);
        order.setPhone(addressBook.getPhone());
        order.setAddress(addressBook.getDetail());
        order.setConsignee(addressBook.getConsignee());
        order.setNumber(String.valueOf(System.currentTimeMillis()));
        order.setUserId(userId);
        order.setStatus(Orders.PENDING_PAYMENT);
        order.setPayStatus(Orders.UN_PAID);
        order.setOrderTime(LocalDateTime.now());
        //向订单表插入1条数据,并获取返回的主键数据
        orderMapper.insert(order);
        Long orderId = order.getId();
        log.info("插入订单表之后返回的主键数据订单id为：{}", orderId);


        //订单明细数据
        List<OrderDetail> orderDetailList = new ArrayList<>();
        for (ShoppingCart cart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(orderId);
            orderDetailList.add(orderDetail);
        }
        //向明细表插入n条数据
        orderDetailMapper.insert(orderDetailList);

        //清理购物车中的数据
        shoppingCartMapper.cleanShoppingCartByUserId(userId);

        //封装返回结果
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(orderId)
                .orderNumber(order.getNumber())
                .orderAmount(order.getAmount())
                .orderTime(order.getOrderTime())
                .build();


        return orderSubmitVO;
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.get(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }


        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));
        //TODO 由于支付功能暂时无法实现，故只要顾客点击确认支付就可认为支付成功！
        //通过websocket向前端推送消息，三个键值对的消息type，orderId和content封装到map集合
        Orders orderInDB = orderMapper.queryOrderByOrderNumber(ordersPaymentDTO.getOrderNumber());
        //随机的把这个订单的状态改为，代付款或者待接单（为了保留一些数据用于测试）
        log.info("由于支付功能暂时无法实现，故只要顾客点击确认支付就可认为支付成功！");

        orderInDB.setStatus(Orders.TO_BE_CONFIRMED);

        log.info("把订单号为{}的订单的状态修改为{}" ,orderInDB.getNumber(),orderInDB.getStatus());
        if (Orders.TO_BE_CONFIRMED.equals(orderInDB.getStatus())){
            orderInDB.setPayStatus(Orders.PAID);
            orderInDB.setCheckoutTime(LocalDateTime.now());
            orderMapper.update(orderInDB);

            Map map = new HashMap();
            map.put("type", 1);
            map.put("orderId", orderInDB.getId());
            map.put("content", "您有新的订单了，订单id是：" + orderInDB.getNumber());
            String jsonString = JSON.toJSONString(map);
            //用WebSocket发送到前端
            webSocketServer.sendToAllClient(jsonString);
        }


        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);
//        //通过websocket向前端推送消息，三个键值对的消息type，orderId和content封装到map集合
//        Map map = new HashMap();
//        map.put("type", 1);
//        map.put("orderId", ordersDB.getId());
//        map.put("content", "您有新的订单了，订单号是：" + ordersDB.getId());
//        String jsonString = JSON.toJSONString(map);
//        //用WebSocket发送到前端
//        webSocketServer.sendToAllClient(jsonString);
    }

    /**
     * 订单的条件分页查询
     *
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult list(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        List<OrderVO> ordersList = orderMapper.pageQuery(ordersPageQueryDTO);

        //TODO 此处使用了for循环嵌套，后续性能优化再考虑拆解嵌套来降低时间复杂度
        List<OrderDetail> orderDetailList = new ArrayList<>();
        for (OrderVO orderVO : ordersList) {
            StringBuilder orderDishes = new StringBuilder();
            orderDetailList = orderDetailMapper.getDetailsByOrderId(orderVO.getId());
            if (orderDetailList != null && orderDetailList.size() >= 1) {
                orderVO.setOrderDetailList(orderDetailList);
                for (int i = 0; i < orderDetailList.size(); i++) {
                    orderDishes.append(orderDetailList.get(i).getName()).append(i == orderDetailList.size() - 1 ? " " : "，");
                }

                orderVO.setOrderDishes(orderDishes.toString());
            }
        }



        Page<OrderVO> ordersPage = (Page<OrderVO>) ordersList;

        return new PageResult(ordersPage.getTotal(), ordersPage.getResult());
    }

    /**
     * 查看订单的详细信息
     *
     * @param id
     * @return
     */
    @Override
    public OrderVO getDetailsById(Long id) {
        //先查订单表的信息
        Orders order = orderMapper.getById(id);
        //再查订单详细表的信息
        List<OrderDetail> orderDetailList = orderDetailMapper.getDetailsByOrderId(id);
        //封装为OrderVO对象后返回
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(order, orderVO);
        orderVO.setOrderDetailList(orderDetailList);
        return orderVO;

    }

    /**
     * 统计各个状态订单的数量
     *
     * @return
     */
    @Override
    public OrderStatisticsVO countOrders() {
        return orderMapper.countOrders();
    }

    /**
     * 取消订单
     * * 业务规则：
     * *
     * * - 待支付和待接单状态下，用户可直接取消订单
     * * - 商家已接单状态下，用户取消订单需电话沟通商家
     * * - 派送中状态下，用户取消订单需电话沟通商家
     * * - 如果在待接单状态下取消订单，需要给用户退款
     * * - 取消订单后需要将订单状态修改为“已取消”
     *
     * @param ordersCancelDTO
     */
    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO) throws Exception {
        Orders orderInDb = orderMapper.getById(ordersCancelDTO.getId());
        if (orderInDb == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        if (orderInDb.getStatus() > 2) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        if (orderInDb.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            //调用微信支付退款接口
            weChatPayUtil.refund(
                    orderInDb.getNumber(), //商户订单号
                    orderInDb.getNumber(), //商户退款单号
                    new BigDecimal(0.01),//退款金额，单位 元
                    new BigDecimal(0.01));//原订单金额

            //支付状态修改为 退款
            orderInDb.setPayStatus(Orders.REFUND);
        }
        orderInDb.setStatus(Orders.CANCELLED);
        orderInDb.setCancelTime(LocalDateTime.now());
        if (orderInDb.getCancelReason() == null) {
            orderInDb.setCancelReason("用户取消");
        }

        orderMapper.update(orderInDb);
    }

    /**
     * 完成订单
     * <p>
     * 业务规则：
     * <p>
     * - 完成订单其实就是将订单状态修改为“已完成”
     * - 只有状态为“派送中”的订单可以执行订单完成操作
     *
     * @param id
     */
    @Override
    public void complete(Long id) {
        //根据id查询出该订单
        Orders orderInDB = orderMapper.getById(id);
        //判断订单的状态是否是派送中
        if (!(Orders.DELIVERY_IN_PROGRESS.equals(orderInDB.getStatus()))) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        orderInDB.setStatus(Orders.COMPLETED);
        orderInDB.setDeliveryTime(LocalDateTime.now());
        orderMapper.update(orderInDB);
    }

    /**
     * 查看订单详情（用户端）
     *
     * @param id
     * @return
     */
    @Override
    public OrderVO orderDetail(Long id) {
        OrderVO orderVo = new OrderVO();
        //先查询订单表的信息
        Orders order = orderMapper.getById(id);
        //再查询订单详细表的信息
        List<OrderDetail> orderDetailList = orderDetailMapper.getDetailsByOrderId(id);
        //封装成OrderVO后返回
        BeanUtils.copyProperties(order, orderVo);
        orderVo.setOrderDetailList(orderDetailList);
        return orderVo;
    }

    /**
     * 再来一单（本质是把订单中的菜品添加到购物车）
     *
     * @param id
     */
    @Override
    @Transactional
    public void repetition(Long id) {
        //根据订单id查出来订单表的信息和订单详细表的信息
        Orders order = orderMapper.getById(id);
        List<OrderDetail> orderDetailList = orderDetailMapper.getDetailsByOrderId(id);
        //把相应的数据封装到购物车对象然后插入购物车表
        ShoppingCart shoppingCart = new ShoppingCart();
        for (OrderDetail orderDetail : orderDetailList) {

            BeanUtils.copyProperties(order, shoppingCart);
            BeanUtils.copyProperties(orderDetail, shoppingCart);
            shoppingCart.setId(null);
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCartMapper.insert(shoppingCart);
        }
    }

    /**
     * 催单
     *
     * @param id
     */
    @Override
    public void reminder(Long id)  {
        Orders orderInDB = orderMapper.getById(id);
        Map map = new HashMap();
        map.put("type", 2);
        map.put("orderId", orderInDB.getId());
        map.put("content", "有顾客催单了，订单号是：" + orderInDB.getNumber());
        String jsonString = JSON.toJSONString(map);
        //用WebSocket发送到前端
        webSocketServer.sendToAllClient(jsonString);
    }

    /**
     * 商家接单
     * 业务规则：
     * <p>
     * - 商家接单其实就是将订单的状态修改为“已接单”
     *
     * @param ordersConfirmDTO
     */
    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        //先查出来数据库中对应的订单
        Orders orderInDB = orderMapper.getById(ordersConfirmDTO.getId());
        if (Orders.TO_BE_CONFIRMED.equals(orderInDB.getStatus())) {
            orderInDB.setStatus(Orders.CONFIRMED);
        }
        orderMapper.update(orderInDB);
    }

    /**
     * 商户拒单
     * <p>
     * 业务规则：
     * <p>
     * - 商家拒单其实就是将订单状态修改为“已取消”
     * - 只有订单处于“待接单”状态时可以执行拒单操作
     * - 商家拒单时需要指定拒单原因
     * - 商家拒单时，如果用户已经完成了支付，需要为用户退款
     *
     * @param ordersRejectionDTO
     */
    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) throws Exception {
        Orders orderInDB = orderMapper.getById(ordersRejectionDTO.getId());
        // 订单只有存在且状态为2（待接单）才可以拒单
        if (!(Orders.TO_BE_CONFIRMED.equals(orderInDB.getStatus()))) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        // 当用户已付款时要为用户退款
        //支付状态
        Integer payStatus = orderInDB.getPayStatus();
        if (payStatus == Orders.PAID) {
            //用户已支付，需要退款
            String refund = weChatPayUtil.refund(
                    orderInDB.getNumber(),
                    orderInDB.getNumber(),
                    new BigDecimal(0.01),
                    new BigDecimal(0.01));
            log.info("申请退款：{}", refund);
        }
        orderInDB.setStatus(Orders.CANCELLED);
        orderInDB.setCancelTime(LocalDateTime.now());
        orderInDB.setRejectionReason(ordersRejectionDTO.getRejectionReason());
        orderMapper.update(orderInDB);
    }

    /**
     * 商家派送
     * 业务规则：
     * <p>
     * - 派送订单其实就是将订单状态修改为“派送中”
     * - 只有状态为“待派送”的订单可以执行派送订单操作
     *
     * @param id
     * @return
     */
    @Override
    public void delivery(Long id) {
        //根据id查询出订单表中相应的订单
        Orders orderInDB = orderMapper.getById(id);
        //判断订单的状态是否是待派送
        if (!(Orders.CONFIRMED.equals(orderInDB.getStatus()))) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        orderInDB.setStatus(Orders.DELIVERY_IN_PROGRESS);
        //将订单的状态修改为待派送
        orderMapper.update(orderInDB);
    }

}
